<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" size="small"  label-position="right" label-width="110px">
            <EdCreateCard title="积分录入">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_black">
                        <el-form-item label="姓名：" prop="userName" :rules="$validate.validates({required:true,msg:'姓名不能为空'})">
                            <el-input v-model="form.userName" style="max-width: 600px" placeholder="请输入姓名" maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号：" prop="userPhone" :rules="$validate.validates({required:true,msg:'手机号不能为空',type:'mobile'})">
                            <el-input v-model="form.userPhone" style="max-width: 600px" placeholder="请输入手机号" maxlength="11"></el-input>
                        </el-form-item>
                        <el-form-item label="房间号：" prop="buildingCode" :rules="$validate.validates({required:true,msg:'楼栋，楼层, 房间号不能为空'})">
                            <el-select v-model="form.buildingCode" style="max-width: 600px" placeholder="楼栋" class="sel-width width100" @change="changeBuildingCode">
                                <el-option
                                        v-for="item in buildingCodeList"
                                        :key="item.code"
                                        :label="item.value"
                                        :value="item.code">
                                </el-option>
                            </el-select>
                            <span class="color085 marginRight8 marginLeft8">栋</span>
                            <el-autocomplete
                                    class="inline-input sel-width"
                                    style="width: 200px;"
                                    :disabled="!form.buildingCode"
                                    v-model="form.roomAddress"
                                    :fetch-suggestions="querySearch"
                                    placeholder="请选择或手动输入"
                                    @select="handleSelect"
                            ></el-autocomplete>
                            <span class="color085 marginRight8 marginLeft8">房号</span>
                        </el-form-item>
                        <el-form-item label="来源：" prop="channelId" :rules="$validate.validates({required:true,msg:'来源不能为空'})">
                            <el-select style="max-width: 600px" v-model="form.channelId" class="width-100" @change="change" placeholder="请选择来源">
                                <el-option
                                        v-for="item in options"
                                        :key="item.channelId"
                                        :label="item.channelName"
                                        :value="item.channelId">
                                </el-option>
                            </el-select>
                            <div class="ruleDetailsList" v-if="pointRuleObj.opposite">
                                <div>① {{pointRuleObj.opposite}}</div>
                                <div v-if="pointRuleObj.isPointRule1">② 有效期至：{{pointRuleObj.effective}} </div>
                                <div v-if="pointRuleObj.isPointRule2">③ 单用户日最大限领：{{pointRuleObj.maxPointDay}}</div>
                            </div>
                        </el-form-item>
                        <el-form-item :label="label" prop="setQuantity" :rules="$validate.validates({required:true,msg: label +'不能为空'})">
                            <el-input style="max-width: 600px" v-model="form.setQuantity" :disabled="!pointRuleObj.opposite" @input="input" :placeholder="'请输入' + label" maxlength="5"></el-input>
                        </el-form-item>

                        <el-form-item label="积分数：" prop="quantity" :rules="$validate.validates({required:true,msg:'积分数不能为空'})">
                            <el-input style="max-width: 600px" v-model="form.quantity" disabled placeholder="输入缴纳金额自动获取积分数"></el-input>
                        </el-form-item>

                        <el-form-item label="凭证：" prop="url" :rules="$validate.validates({required:true,msg:'凭证不能为空'})">
                            <ed-upload-single v-model="form.url" @pic-url="picUrl" ref="edUploadSingle"></ed-upload-single>
                        </el-form-item>

                        <el-form-item class="paddingBottom145" style="margin-left: 110px">
                            <el-button type="primary" @click="onSubmit('formRef')" :loading="disabled">保存</el-button>
                            <el-button @click="reset" class="Class1MarginLeft8">重置</el-button>
                        </el-form-item>
                </div>
            </EdCreateCard>
        </el-form>
        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue"></ed-confirm-delete>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import {queryApplet ,addRecords} from "src/api/activity";
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import EdUploadSingle from "src/components/EdUploadSingle.vue";
    import {doorplateList ,webDoorplateList} from "src/api/resources";
    export default {
        name: "RecordCreate",
        components:{
            EdConfirmDelete,
            EdUploadSingle,
            EdCreateCard
        },
        data(){
            return{
                form:{
                    userName:"",
                    userPhone:"",
                    buildingCode:"",
                    roomAddress:"",
                    setQuantity:null,
                    quantity:null,
                    source:"",
                    ruleType:"",
                    channelId:"",
                    inputType:1,
                    pid:"",
                    ruleId:"",
                    url:"",
                },
                disabled:false,
                options:[],
                buildingCodeList:[],
                pointRuleObj:{
                    isPointRule1:false,
                    isPointRule2:false,
                },
                label:"缴纳金额",
                measures:[],
                measure:null,

                createData:[]
            }
        },
        mounted(){
            queryApplet({applet:true}).then(response => {
                if(response.code == 20000 && response.data) {
                    this.options = response.data;
                }
            });

            doorplateList({residentialId:this.$store.getters.vid}).then(response => {
                if(response.code == 20000 && response.data){
                    if(response.data.buildings){
                        for(let key in response.data.buildings[this.$store.getters.vid]){
                            this.buildingCodeList.push({
                                value:response.data.buildings[this.$store.getters.vid][key].value,
                                code:response.data.buildings[this.$store.getters.vid][key].code
                            })
                        }
                    }
                }
            })
        },
        methods:{
            picUrl(url){
                this.form.url = url;
                this.$refs.formRef.validateField("url");
            },
            change(val){
                for (let i=0;i<this.options.length;i++){
                    if(val == this.options[i].channelId){
                        this.form.source = this.options[i].channelName;
                        this.form.ruleType = this.options[i].ruleType;
                        this.form.pid = this.options[i].pid;
                        this.form.channelId = this.options[i].channelId;
                        this.form.ruleId = this.options[i].ruleId;

                        if(this.options[i].ruleContent){
                            this.pointRuleObj.opposite = JSON.parse(this.options[i].ruleContent).opposite ? JSON.parse(this.options[i].ruleContent).opposite : "";
                            this.pointRuleObj.effective = JSON.parse(this.options[i].ruleContent).effective ? JSON.parse(this.options[i].ruleContent).effective : "";
                            this.pointRuleObj.maxPointDay = JSON.parse(this.options[i].ruleContent).maxPointDay ? JSON.parse(this.options[i].ruleContent).maxPointDay : "";
                            this.pointRuleObj.isPointRule1 = !!JSON.parse(this.options[i].ruleContent).effective;
                            this.pointRuleObj.isPointRule2 = !!JSON.parse(this.options[i].ruleContent).maxPointDay;
                            this.measures = JSON.parse(this.options[i].ruleContent).measures;
                            this.measure = JSON.parse(this.options[i].ruleContent).measure;
                            this.setQuantityFn(this.measure,this.measures)
                        }else {
                            this.$message.info({
                                message: '请先绑定积分规则再进行缴费',
                                duration: 2000,
                                center:true
                            });
                            this.pointRuleObj = {
                                isPointRule1:false,
                                isPointRule2:false,
                            };
                            this.$set(this.form,"quantity","");
                            this.$set(this.form,"setQuantity","")
                        }
                    }
                }
            },
            webDoorplateList(buildingCode){
                this.createData = [];
                webDoorplateList({buildingCode:buildingCode}).then(response => {
                    if(response.code == 20000) {
                        for (let i=0;i<response.data.length;i++){
                            this.createData.push({
                                value: response.data[i].address,
                                roomId: response.data[i].roomId,
                            })
                        }
                    }
                })
            },
            querySearch(queryString, cb) {
                let restaurants = this.createData;
                let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) {
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
                };
            },
            handleSelect(val){
                this.form.roomId = val.roomId;
            },
            changeBuildingCode(evn){
                for (let i=0;i<this.buildingCodeList.length;i++){
                    if(this.buildingCodeList[i].code == evn){
                        this.webDoorplateList(this.buildingCodeList[i].value)
                    }
                }
                this.form.roomAddress = ""
            },
            input(){
                this.$set(this.form,"setQuantity",this.$validate.check_num(this.form.setQuantity));
                this.setQuantityFn(this.measure,this.measures)
            },
            setQuantityFn(measure,measures){
                let one = measures[0];
                let two = measures[1];
                if(measure == 0){
                    this.label = "缴纳金额";
                }else if(measure == 1){
                    this.label = "完成次数";
                }else if(measure == 2){
                    this.label = "垃圾重量";
                }
                this.form.quantity = this.$utilsSet.accMul(two / one , this.form.setQuantity);
            },
            onSubmit(formName) {
                this.$refs[formName].validate((valid) => {

                    if (valid) {
                        this.disabled = true;
                        window.setTimeout(() => {
                            this.disabled = false
                        }, 2000);
                        this.form.quantity = parseInt(this.form.quantity);
                        addRecords(this.form).then(response => {
                            if(response.code == 20000) {
                                if(response.data.confirmation){
                                    this.$refs.confirmDeleteRef.open("积分录入二次确认",response.data.message,"warning")
                                }else {
                                    this.$message.success({
                                        message: '已成功录入积分 即将返回积分列表',
                                        duration: 2000,
                                        center:true
                                    });

                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }

                            }
                        })
                    }
                })
            },
            confirmDeleteTrue(){
                this.form.confirmation = true;
                addRecords(this.form).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '已成功录入积分 即将返回积分列表',
                            duration: 2000,
                            center:true
                        });

                        window.setTimeout(() => {
                            this.$utilsSet.goBack(this.$router);
                        }, 600)

                    }
                })
            },
            reset(){
                this.form = {
                    userName:"",
                    userPhone:"",
                    buildingCode:"",
                    roomAddress:"",
                    setQuantity:null,
                    quantity:null,
                    source:"",
                    ruleType:"",
                    channelId:"",
                    inputType:1,
                    pid:"",
                    ruleId:"",
                    url:"",
                };
                this.label = "缴纳金额";
                this.measures = [];
                this.measure = null;
                this.pointRuleObj = {
                    isPointRule1:false,
                    isPointRule2:false,
                };
                this.$refs.formRef.resetFields();
                this.$refs.edUploadSingle.setPic("");
            }
        }
    }
</script>

<style lang="scss">
    .village{
        .village-building-input{
            .el-input{
                width: calc(100% - 20px)
            }
            span{
                width: 20px;color: #606266;
            }
        }
        .village-area-input{
            .el-input{
                width: calc(100% - 80px)
            }
            span{
                width: 80px;
                color: #606266;
            }
        }
    }
</style>

<style scoped lang="scss">
    .ruleDetailsList{
        background: #E6F7FF;
        opacity: 1;
        border-radius: 2px;
        padding: 12px;
        margin:9px 0 0 0;
        div {
            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
            color: rgba(0, 0, 0, 0.85);
        }
    }
</style>